package com.jfreer.security;

import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.vote.AbstractAccessDecisionManager;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.FilterInvocation;

import java.util.Collection;

/**
 * User: landy
 * Date: 15/6/1
 * Time: 下午10:41
 */
public class MyAccessDecisionManager extends AbstractAccessDecisionManager {
    @Override
    public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> collection) throws AccessDeniedException, InsufficientAuthenticationException {
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        boolean hasRole = false;
        for (ConfigAttribute one : collection) {
            final String oneName = one.getAttribute();
            boolean rst = Iterables.any(authorities, new Predicate<GrantedAuthority>() {
                @Override
                public boolean apply(GrantedAuthority input) {
                    return input.getAuthority().equals(oneName);
                }
            });
            if (rst) {
                hasRole = true;
                break;
            }
        }
        if (!hasRole) {
            String requestUrl = ((FilterInvocation) o).getRequestUrl();
            throw new AccessDeniedException(requestUrl);
        }
    }
}
